package main

import (
	"fmt"
	"net/http"
	"sen-golang-study/go_game_study/hero_story_go_server/common/log"
	appServices "sen-golang-study/go_game_study/hero_story_go_server/gateway_server/internal/application/services"
	"sen-golang-study/go_game_study/hero_story_go_server/gateway_server/internal/domain/entity"
	"sen-golang-study/go_game_study/hero_story_go_server/gateway_server/internal/domain/repository"
	"sen-golang-study/go_game_study/hero_story_go_server/gateway_server/internal/infrastructure/config"
	"sen-golang-study/go_game_study/hero_story_go_server/gateway_server/internal/interfaces/websocket"
)

// 游戏前端地址：http://cdn0001.afrxvk.cn/hero_story/demo/step040/index.html?serverAddr=127.0.0.1:54321
func main() {
	// 初始化配置
	cfg := config.NewConfig()
	fmt.Printf("启动网关服务，监听地址: %s，etcd端点: %s\n", cfg.ListenAddr, cfg.EtcdEndpoints)

	// 初始化基础设施层
	sessionRepo := repository.NewSessionRepository()
	serverConnRepo := repository.NewServerConnRepository(sessionRepo)
	messageRouter := entity.NewMessageRouter()
	serverSelector := entity.NewServerSelector()

	// 初始化应用层
	gatewayService := appServices.NewGatewayService(sessionRepo, serverConnRepo, messageRouter, serverSelector)
	discoveryService := appServices.NewDiscoveryService(cfg.EtcdEndpoints, gatewayService)

	// 启动服务发现
	if discoveryService != nil {
		discoveryService.StartDiscovery()
	}

	// 初始化接口层
	upgrader := websocket.NewUpgrader()
	handler := websocket.NewHandler(upgrader, gatewayService)

	// 注册路由
	http.HandleFunc("/websocket", handler.HandleWebSocket)

	// 启动HTTP服务器
	log.Info("HTTP服务器启动，监听地址: %s", cfg.ListenAddr)
	_ = http.ListenAndServe(cfg.ListenAddr, nil)
}
